package com.example.scaffolding.composer

import android.content.Context
import android.graphics.BitmapFactory
import android.util.Log
import android.widget.ImageView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.example.scaffolding.composer.worker.ImageDownloadWorker
import com.example.scaffolding.composer.worker.ImageLoadWorker
import com.example.scaffolding.util.EventListener


// ...and the result key:
const val KEY_RESULT = "result"
const val KEY_BITMAP_RESULT = "result"

class ImageComposer {

    val Progress = "Progress"

    private var mUrlOne: String? = null
    private var mUrlTwo: String? = null
    private var mUrlList = mutableListOf<String>()

    private var mListenerList = mutableListOf<EventListener<String>>()

    private var mFileUrlList = mutableListOf<String>()

    fun addInput(url: String, listener: EventListener<String>) {
        Log.d(TAG, "url = $url")
        mUrlList.add(url)
        mListenerList.add(listener)
    }

    fun setOutputListener(listener: EventListener<String>) {
        mListenerList.add(listener)
    }


    fun createWork(myContext: Context): Array<LiveData<WorkInfo>> {
        val downloadWorkRequestOne = OneTimeWorkRequestBuilder<ImageDownloadWorker>()
            .setInputData(
                workDataOf(
                    "IMAGE_URI" to mUrlList[0]
                )
            )
            .build()

        val downloadWorkRequestTwo = OneTimeWorkRequestBuilder<ImageDownloadWorker>()
            .setInputData(
                workDataOf(
                    "IMAGE_URI" to mUrlList[1]
                )
            )
            .build()

        val loadImageWorkRequestOne = OneTimeWorkRequestBuilder<ImageLoadWorker>().build()

        val loadImageWorkRequestTwo = OneTimeWorkRequestBuilder<ImageLoadWorker>().build()

        WorkManager
            .getInstance(myContext)
            .beginWith(downloadWorkRequestOne)
            .then(loadImageWorkRequestOne)
            .enqueue()

        WorkManager
            .getInstance(myContext)
            .beginWith(downloadWorkRequestTwo)
            .then(loadImageWorkRequestTwo)
            .enqueue()

        return arrayOf(
            WorkManager.getInstance(myContext)
                // requestId is the WorkRequest id
                .getWorkInfoByIdLiveData(downloadWorkRequestOne.id),
            WorkManager.getInstance(myContext)
                // requestId is the WorkRequest id
                .getWorkInfoByIdLiveData(downloadWorkRequestTwo.id),
            WorkManager.getInstance(myContext)
                .getWorkInfoByIdLiveData(loadImageWorkRequestOne.id),
            WorkManager.getInstance(myContext)
                .getWorkInfoByIdLiveData(loadImageWorkRequestTwo.id)
        )

    }

    fun start(
        myContext: Context,
        viewLifecycleOwner: LifecycleOwner,
        imageView1: ImageView,
        imageView2: ImageView
    ) {

        createWork(myContext).takeIf { it.size == 4 }?.let {

            it[0].observe(viewLifecycleOwner, androidx.lifecycle.Observer { workInfo: WorkInfo? ->
                if (workInfo != null) {
                    val progress = workInfo.progress
                    val value: Int = progress.getInt(Progress, 100)
//                    Log.d(TAG, "value = $value")
                    // Do something with progress information
                    mListenerList[0].onProgress(value)


                    if (workInfo.state.isFinished) {
                        val myResult: String? = workInfo.outputData.getString(KEY_RESULT)
                        // ... do something with the result ...
                        myResult?.let {
                            mFileUrlList.add(it)
                        }
                        Log.d(TAG, "downloadWorkRequest One onSuccess = $myResult")
                        mListenerList[0].onSuccess("")
                    }
                }
            })

            it[1].observe(viewLifecycleOwner, androidx.lifecycle.Observer { workInfo: WorkInfo? ->
                if (workInfo != null) {
                    val progress = workInfo.progress
                    val value = progress.getInt(Progress, 100)
                    // Do something with progress information
                    mListenerList[1].onProgress(value)

                    if (workInfo.state.isFinished) {
                        val myResult: String? = workInfo.outputData.getString(KEY_RESULT)
                        // ... do something with the result ...
                        myResult?.let {
                            mFileUrlList.add(it)
                        }
                        Log.d(TAG, "downloadWorkRequest Two onSuccess = $myResult")
                        mListenerList[1].onSuccess("")
                    }
                }
            })

            it[2].observe(viewLifecycleOwner, androidx.lifecycle.Observer { workInfo: WorkInfo? ->
                if (workInfo != null && workInfo.state.isFinished) {
                    val myResult: String? = workInfo.outputData.getString(KEY_BITMAP_RESULT)
                    // ... do something with the result ...
                    myResult?.let {
                        //decodeFile从指定路径解析图片
                        val bitmap = BitmapFactory.decodeFile(myResult)
                        imageView1.setImageBitmap(bitmap)
                    }
                }
            })
            it[3].observe(viewLifecycleOwner, androidx.lifecycle.Observer { workInfo: WorkInfo? ->
                if (workInfo != null && workInfo.state.isFinished) {
                    val myResult: String? = workInfo.outputData.getString(KEY_BITMAP_RESULT)
                    // ... do something with the result ...
                    myResult?.let {
                        //decodeFile从指定路径解析图片
                        val bitmap = BitmapFactory.decodeFile(myResult)
                        imageView2.setImageBitmap(bitmap)
                    }
                }
            })
        }

    }

    fun stop() {
        // TODO do something
    }

    companion object {
        private const val TAG = "ImageComposer"
    }

}